<template>
	<!-- 发布商品 -->
	<view class="content">
		<u--form labelPosition="left" :model="form" ref="form1">
			<!-- 	<view class="w-80">
				<u-button @click="addressClick" type="primary" size="small">默认写入身份信息</u-button>
			</view> -->
			<u-form-item labelWidth="180" label="产品类型" borderBottom>
				<u-radio-group v-model="form.goodsType" placement="row">
					<view class="flex wrap">
						<view class="w-50 mtb-12">
							<u-radio activeColor="red" size="35" iconSize="30" name="0" labelSize="35" label="狗粮"></u-radio>
						</view>
						<view class="w-50 mtb-12">
							<u-radio activeColor="blue" size="35" iconSize="30" name="1" labelSize="35" label="猫粮"></u-radio>
						</view>
						<view class="w-50 ">
							<u-radio activeColor="yellow" size="35" iconSize="30" name="2" labelSize="35" label="宠物日用"></u-radio>
						</view>
						<view class="w-50">
							<u-radio activeColor="green" size="35" iconSize="30" name="3" labelSize="35" label="营养保健"></u-radio>
						</view>
					</view>
				</u-radio-group>
			</u-form-item>
			<u-form-item labelWidth="210" label="产品适用宠物" borderBottom>
				<u-radio-group v-model="form.activePet" placement="row">
					<view class="flex wrap">
						<view class="w-50 mtb-12">
							<u-radio activeColor="red" size="35" iconSize="30" name="0" labelSize="35" label="狗"></u-radio>
						</view>
						<view class="w-50 mtb-12">
							<u-radio activeColor="blue" size="35" iconSize="30" name="1" labelSize="35" label="猫"></u-radio>
						</view>
						<view class="w-50 ">
							<u-radio activeColor="yellow" size="35" iconSize="30" name="2" labelSize="35" label="其他"></u-radio>
						</view>
						<view class="w-50">
							<u-radio activeColor="green" size="35" iconSize="30" name="3" labelSize="35" label="猫狗皆可"></u-radio>
						</view>
					</view>
				</u-radio-group>
			</u-form-item>
			<u-form-item labelWidth="180" label="产品名称" borderBottom>
				<u--input v-model="form.name" border="none" placeholder="产品名称"></u--input>
			</u-form-item>
			<u-form-item labelWidth="180" label="产品价格" borderBottom>
				<view class="flex">
					<view class="w-80">
						<u--input v-model="form.money" border="none" type="number" maxlength="5" placeholder="产品价格/元"></u--input>
					</view>
					<text>元</text>
				</view>
			</u-form-item>
			<u-form-item labelWidth="180" label="产品规格" borderBottom>
				<view class="flex">
					<view class="w-80">
						<u--input v-model="form.weight" border="none" type="number" maxlength="5" placeholder="产品重量/千克"></u--input>
					</view>
					<text>kg</text>
				</view>
			</u-form-item>
			<u-form-item labelWidth="180" label="库存" borderBottom>
				<u--input v-model="form.num" border="none" type="number" maxlength="5" placeholder="库存量"></u--input>
			</u-form-item>
			<u-form-item labelWidth="180" label="适用年龄段" borderBottom>
				<u--input v-model="form.old" border="none" placeholder="幼犬专用、金毛幼犬专用..."></u--input>
			</u-form-item>
			<u-form-item labelWidth="180" label="详情描述" borderBottom>
				<u--input v-model="form.detail" border="none" placeholder="产品详情描述"></u--input>
			</u-form-item>
			<u-form-item labelWidth="180" label="特殊效果" borderBottom>
				<u--input v-model="form.note" border="none" placeholder="调理肠胃、健骨补钙..."></u--input>
			</u-form-item>
			<view class="miantilte mtb-12">
				添加商品轮播图片（{{fileList.length}}/5）
			</view>
			<view class="sub-title-text">
				添加商品轮播图片可以提高您的曝光度,默认图为示例，直接点击图片即可多传
			</view>
			<view class="uni-form-item upload flex wrap">
				<block v-if="fileList.length">
					<view v-for="(item,index) in fileList" :key="index" class="imgwrap relative">
						<image :src="item" mode="widthFix" class="uploadImg" @click="choose(0)"></image>
						<view class="index absolute">
							{{index+1}}
						</view>
						<view class="x absolute" @click.self="del(item,index)">
							<image src="../../../static/icon/del.png" mode=""></image>
						</view>
					</view>
				</block>
				<image src="../../../static/icon/add.png" class="addImg" @click="choose(0)" alt="" v-else>
				</image>
			</view>
			<view class="miantilte mtb-12">
				添加商品详情图片（{{detailList.length}}/5）
			</view>
			<view class="sub-title-text">
				添加商品详情图片可以提高您的销量,默认图为示例，直接点击图片即可多传
			</view>
			<view class="uni-form-item upload flex wrap">
				<block v-if="detailList.length">
					<view v-for="(item,index) in detailList" :key="index" class="imgwrap relative">
						<image :src="item" mode="widthFix" class="uploadImg" @click="choose(1)"></image>
						<view class="index absolute">
							{{index+1}}
						</view>
						<view class="x absolute" @click.self="del(item,index)">
							<image src="../../../static/icon/del.png" mode=""></image>
						</view>
					</view>
				</block>
				<image src="../../../static/icon/add.png" class="addImg" @click="choose(1)" alt="" v-else>
				</image>
			</view>
			<view class="isShow">
				<checkbox-group @change="isVideo">
					<label>
						<checkbox value="1" checked="true" />是否上传视频？
					</label>
				</checkbox-group>
			</view>
			<view class="videos" v-if="videoLock">
				<view class="miantilte mtb-12">
					上传视频(仅可上传一条)
				</view>
				<view class="uploadVideo w-80" style="min-height: 400rpx;background-color: aliceblue;" @click="uploadVideo"
					v-if="!video">
					<image src="../../../static/icon/add.png" style="width: 220rpx;height: 220rpx;margin-top: 100rpx;">
				</view>
				<view class="relative" v-else>
					<!-- <video style="width: 100%;" controls src="cloud://animal-4g5ks6ct0e7f251e.616e-animal-4g5ks6ct0e7f251e-1315698572/belostvideo/狗3.mp4"></video> -->
					<video style="width: 100%;" controls :src="video"></video>
					<view class="absolute x" style="top:20rpx;right:20rpx" @click="delVideo">
						<image src="../../../static/icon/del.png" mode="" style="width: 80rpx;height: 80rpx;"></image>
					</view>
				</view>
			</view>
		</u--form>
		<u-button type="success" text="确认发布" customStyle="margin-top: 50px" @click="submit"></u-button>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				fileList: [
					"https://616e-animal-4g5ks6ct0e7f251e-1315698572.tcb.qcloud.la/logo.png?sign=ffe3e111a4b0466169e3cee81c1a2b4f&t=1721984968"
				], //轮播图list
				show: false,
				form: {
					name: "",
					weight: "",
					old: "",
					detail: "",
					note: "",
					money: "",
					goodsType: 0,
					activePet: 0,
					num: ""
				},
				video: null,
				videoLock: true,
				detailList: [
					"https://616e-animal-4g5ks6ct0e7f251e-1315698572.tcb.qcloud.la/logo.png?sign=ffe3e111a4b0466169e3cee81c1a2b4f&t=1721984968"
				], //详情图list
			}
		},
		onLoad() {

		},
		methods: {
			async submit() {
				console.log('form发生了submit事件，携带数据为：' + JSON.stringify(this.form), this.fileList)
				uni.showLoading({
					mask: true,
					title: "上传中"
				})
				let promises = [];
				for (let i = 0; i < this.fileList.length; i++) {
					let filePath = this.fileList[i];
					// 将每个上传操作添加到promises数组中
					promises.push(this.uploadFile.call(this, filePath)); // 使用call确保this指向正确
				}
				let fileIDs = await Promise.all(promises)
				let promises2 = [];
				for (let i = 0; i < this.detailList.length; i++) {
					let filePath = this.detailList[i];
					// 将每个上传操作添加到promises数组中
					promises2.push(this.uploadFile.call(this, filePath)); // 使用call确保this指向正确
				}
				let fileIDs2 = await Promise.all(promises2)
				let videoPath = null
				if (this.videoLock) {
					videoPath = await this.uploadVideoFun(this.video)
				}
				let res = await wx.cloud.callFunction({
					name: 'logins',
					data: {
						useName: 'addGoods', //捡到、找到
						...this.form,
						uploadDate: this.$formatDateTime(new Date(), 1),
						swiperList: fileIDs,
						detailList: fileIDs2,
						videoSrc: videoPath
					}
				})
				uni.hideLoading()
				uni.showToast({
					title: '发布成功',
					icon: 'success',
					duration: 2000,
					success() {
						console.log("成功")
					}
				})
				uni.navigateBack()
			},
			isVideo(e) {
				console.log('e: ', e.detail.value);
				if (!e.detail.value.length) {
					this.videoLock = false
				} else {
					this.videoLock = true
				}
			},
			uploadFile(filePath) {
				return new Promise((resolve, reject) => {
					let fileName = filePath.split('/').pop(); // 获取文件名
					this.$clould.uploadFile({
						cloudPath: 'bolost/' + fileName,
						filePath: filePath,
						success: res => {
							resolve(res.fileID);
						},
						fail: err => {
							uni.hideLoading()
							uni.showToast({
								title: '请上传图片',
								icon: 'error',
								duration: 2000
							})
							reject(err);
						}
					});
				});
			},
			choose(num) {
				uni.chooseMedia({
					count: 5,
					mediaType: ['image'],
					sourceType: ['album'],
					success: (res) => {
						let filelist = res.tempFiles
						let arr = []
						for (let i = 0; i < filelist.length; i++) {
							let filePath = filelist[i].tempFilePath
							arr.push(filePath)
						}
						if (num) {
							setTimeout(() => {
								this.detailList = arr.reverse()
								console.log("res:---", this.detailList, arr)
							}, 0)
						} else {
							setTimeout(() => {
								this.fileList = arr.reverse()
								console.log("res:---", this.fileList, arr)
							}, 0)
						}
					}
				})
			},
			uploadVideo() {
				uni.chooseMedia({
					count: 1,
					mediaType: ['video'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						let filelist = res.tempFiles
						this.video = filelist[0].tempFilePath
					}
				})
			},
			delVideo() {
				this.video = null
			},
			del(item, index) {
				this.fileList = this.fileList.filter(ite => ite !== item)
			},
			addressClick() {
				uni.chooseAddress({
					success: (res) => {
						// console.log(res.userName)
						// console.log(res.postalCode)
						// console.log(res.provinceName)
						// console.log(res.cityName)
						// console.log(res.countyName)
						// console.log(res.detailInfo)
						// console.log(res.nationalCode)
						// console.log(res.telNumber)
						this.form.username = res.userName
						this.form.tel = res.telNumber
						this.form.address = res.provinceName + res.cityName + res.countyName + res.detailInfo
					}
				})
			},
			checkDate(e) {
				console.log(e);
				// this.form.date=e[0]
				// this.show=false
			},
			uploadVideoFun(filePath) {
				return new Promise((resolve, reject) => {
					let fileName = filePath.split('/').pop(); // 获取文件名
					this.$clould.uploadFile({
						cloudPath: 'belostvideo/' + fileName,
						filePath: filePath,
						success: res => {
							resolve(res.fileID);
						},
						fail: err => {
							reject(err);
						}
					});
				});
			}

		}
	}
</script>

<style scoped lang="scss">
	.content {
		text-align: center;
		min-height: 100vh;
		padding: $uni-spacing-row-base;
		background: linear-gradient(#9baeff, #007aff);

		.uni-form-item {
			padding: 20rpx 0;
		}

		.upload {
			.addImg {
				width: 220rpx;
				height: 220rpx;
				margin: 8rpx;
				// width: 100%;
			}

			.imgwrap {
				.uploadImg {
					width: 220rpx;
					margin: 8rpx;
					// width: 100%;
				}

				.index {
					bottom: 10rpx;
					left: 10rpx;
				}

				.x {
					top: 10rpx;
					right: 10rpx;

					image {
						width: 64rpx;
						height: 64rpx;
					}
				}
			}
		}
	}
</style>